#pragma once
#include <memory>
#include <grpcpp/grpcpp.h>
#include "framework/service_interface.h"
#include "service_rpc.grpc.pb.h"

namespace cpp_backend {
namespace framework {

/**
 * @brief gRPC服务实现（内部类）
 * 
 * 负责：
 * - 处理gRPC请求
 * - 转换gRPC消息 ↔ 框架Request/Response
 * - 调用业务Service
 */
class ServiceRPCImpl final : public service_rpc::ServiceRPC::Service {
public:
    explicit ServiceRPCImpl(IService* business_service)
        : business_service_(business_service)
        , start_time_(std::chrono::system_clock::now()) {}
    
    /**
     * @brief 处理RPC调用
     */
    grpc::Status Call(
        grpc::ServerContext* context,
        const service_rpc::ServiceRequest* grpc_request,
        service_rpc::ServiceResponse* grpc_response
    ) override;
    
    /**
     * @brief 健康检查
     */
    grpc::Status HealthCheck(
        grpc::ServerContext* context,
        const service_rpc::HealthCheckRequest* request,
        service_rpc::HealthCheckResponse* response
    ) override;
    
private:
    IService* business_service_;
    std::chrono::system_clock::time_point start_time_;
    
    /**
     * @brief 转换gRPC请求 → 框架Request
     */
    Request convert_from_grpc_request(const service_rpc::ServiceRequest* grpc_req);
    
    /**
     * @brief 转换框架Response → gRPC响应
     */
    void convert_to_grpc_response(
        const Response& resp,
        service_rpc::ServiceResponse* grpc_resp
    );
    
    /**
     * @brief 获取运行时长（秒）
     */
    int64_t get_uptime_seconds() const {
        auto now = std::chrono::system_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::seconds>(
            now - start_time_
        );
        return duration.count();
    }
};

/**
 * @brief gRPC服务器封装
 * 
 * 负责：
 * - 启动gRPC服务器
 * - 注册业务Service
 * - 优雅关闭
 */
class ServiceServer {
public:
    explicit ServiceServer(int port) : port_(port) {}
    
    ~ServiceServer() {
        stop();
    }
    
    /**
     * @brief 注册业务服务
     * @param service 业务服务实例（必须在start前调用）
     */
    void register_service(IService* service);
    
    /**
     * @brief 启动gRPC服务器
     * @return 是否启动成功
     */
    bool start();
    
    /**
     * @brief 等待关闭信号
     */
    void wait_for_shutdown();
    
    /**
     * @brief 停止服务器
     */
    void stop();
    
    /**
     * @brief 获取端口
     */
    int port() const { return port_; }
    
private:
    int port_;
    std::unique_ptr<grpc::Server> grpc_server_;
    std::unique_ptr<ServiceRPCImpl> service_impl_;
};

} // namespace framework
} // namespace cpp_backend
